import React, { useEffect, useState } from 'react';
import {
  Modal,
  Tabs,
  Typography,
  List,
  Avatar,
  Space,
  Tag,
  Button,
  Divider,
  Image,
  Spin,
  message,
} from 'antd';
import {
  LikeOutlined,
  CommentOutlined,
  ShareAltOutlined,
  EyeOutlined,
  EditOutlined,
  StarOutlined,
  StarFilled,
  LinkOutlined,
} from '@ant-design/icons';
import { HotItemDetail, Comment } from '../../../types/hotRadar';
import { platformConfig } from '../../../constants/platforms';
import { hotRadarService } from '../../../services/hotRadar.service';
import { useHotRadarStore } from '../../../stores/hotRadar.store';
import { HeatTrendChart } from '../HeatTrendChart';
import './style.css';

const { Title, Text, Paragraph, Link } = Typography;
const { TabPane } = Tabs;

interface HotItemDetailModalProps {
  visible: boolean;
  item: any;
  onClose: () => void;
}

export const HotItemDetailModal: React.FC<HotItemDetailModalProps> = ({
  visible,
  item,
  onClose,
}) => {
  const [loading, setLoading] = useState(false);
  const [detailData, setDetailData] = useState<HotItemDetail | null>(null);
  const [activeTab, setActiveTab] = useState('detail');
  const { favoriteIds, toggleFavorite } = useHotRadarStore();

  const isFavorited = item && favoriteIds.includes(item.item_id);
  const platformInfo = item && platformConfig[item.platform];

  useEffect(() => {
    if (visible && item) {
      fetchDetailData();
    }
  }, [visible, item]);

  const fetchDetailData = async () => {
    if (!item) return;
    
    setLoading(true);
    try {
      const data = await hotRadarService.getHotItemDetail(item.item_id, item.platform);
      setDetailData(data);
    } catch (error) {
      message.error('获取详情数据失败');
      console.error('Failed to fetch detail:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleFavorite = () => {
    if (item) {
      toggleFavorite(item.item_id);
    }
  };

  const handleCreateContent = () => {
    if (item) {
      window.location.href = `/editor?hotItemId=${item.item_id}`;
    }
  };

  const handleOpenSource = () => {
    if (item?.url) {
      window.open(item.url, '_blank');
    }
  };

  const renderComments = (comments: Comment[] = []) => (
    <List
      className="comment-list"
      itemLayout="horizontal"
      dataSource={comments}
      renderItem={(comment) => (
        <List.Item>
          <List.Item.Meta
            avatar={<Avatar>{comment.author[0]}</Avatar>}
            title={
              <Space>
                <Text strong>{comment.author}</Text>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {new Date(comment.created_at).toLocaleString('zh-CN')}
                </Text>
              </Space>
            }
            description={
              <>
                <Paragraph>{comment.content}</Paragraph>
                <Space>
                  <Button
                    size="small"
                    type="text"
                    icon={<LikeOutlined />}
                  >
                    {comment.like_count}
                  </Button>
                  {comment.reply_count !== undefined && (
                    <Button
                      size="small"
                      type="text"
                      icon={<CommentOutlined />}
                    >
                      {comment.reply_count}
                    </Button>
                  )}
                </Space>
              </>
            }
          />
        </List.Item>
      )}
    />
  );

  if (!item) return null;

  return (
    <Modal
      title={
        <div className="modal-header">
          <Space>
            <Tag color={platformInfo?.color}>
              {platformInfo?.icon} {platformInfo?.name}
            </Tag>
            {item.category && <Tag>{item.category}</Tag>}
            <Tag color="red">#{item.rank}</Tag>
          </Space>
        </div>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={[
        <Button
          key="favorite"
          icon={isFavorited ? <StarFilled /> : <StarOutlined />}
          onClick={handleFavorite}
        >
          {isFavorited ? '已收藏' : '收藏'}
        </Button>,
        <Button
          key="source"
          icon={<LinkOutlined />}
          onClick={handleOpenSource}
        >
          查看原文
        </Button>,
        <Button
          key="create"
          type="primary"
          icon={<EditOutlined />}
          onClick={handleCreateContent}
        >
          开始创作
        </Button>,
      ]}
    >
      <Spin spinning={loading}>
        <div className="detail-modal-content">
          <Title level={4}>{item.title}</Title>
          
          {detailData && (
            <div className="detail-stats">
              <Space size="large">
                {detailData.view_count !== undefined && (
                  <span>
                    <EyeOutlined /> {detailData.view_count}
                  </span>
                )}
                {detailData.like_count !== undefined && (
                  <span>
                    <LikeOutlined /> {detailData.like_count}
                  </span>
                )}
                {detailData.comment_count !== undefined && (
                  <span>
                    <CommentOutlined /> {detailData.comment_count}
                  </span>
                )}
                {detailData.share_count !== undefined && (
                  <span>
                    <ShareAltOutlined /> {detailData.share_count}
                  </span>
                )}
              </Space>
            </div>
          )}

          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab="详情" key="detail">
              <div className="detail-content">
                {item.excerpt && (
                  <Paragraph>{item.excerpt}</Paragraph>
                )}
                
                {detailData?.content && (
                  <>
                    <Divider />
                    <Paragraph>{detailData.content}</Paragraph>
                  </>
                )}

                {detailData?.media_urls && detailData.media_urls.length > 0 && (
                  <>
                    <Divider />
                    <div className="media-gallery">
                      <Image.PreviewGroup>
                        {detailData.media_urls.map((url, index) => (
                          <Image
                            key={index}
                            width={200}
                            src={url}
                            style={{ marginRight: 8, marginBottom: 8 }}
                          />
                        ))}
                      </Image.PreviewGroup>
                    </div>
                  </>
                )}

                {detailData?.tags && detailData.tags.length > 0 && (
                  <>
                    <Divider />
                    <Space wrap>
                      {detailData.tags.map((tag) => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </Space>
                  </>
                )}
              </div>
            </TabPane>

            <TabPane tab="评论" key="comments">
              {detailData?.comments && detailData.comments.length > 0 ? (
                renderComments(detailData.comments)
              ) : (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Text type="secondary">暂无评论数据</Text>
                </div>
              )}
            </TabPane>

            <TabPane tab="趋势" key="trend">
              <HeatTrendChart itemId={item.item_id} />
            </TabPane>
          </Tabs>
        </div>
      </Spin>
    </Modal>
  );
};